/**
 * FormFornecedor.java
 * Copyright (C) 2009 Jose Mauro da Silva Sandy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * FormFornecedor.java
 *
 * Created on 14/06/2009, 00:05:45
 */

package frames;

import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import negocio.pessoas.*;
import utils.*;

/**
 *
 * @author jmsandy
 */
public class FormFornecedor extends javax.swing.JDialog {

    //<editor-fold defaultstate="collapsed" desc="FIELDS">
    private Fornecedor fornecedor      = null;
    private Endereco endereco          = null;
    private ArrayList lstObj           = null;
    private ArrayList<Telefone> lstTel = null;
    private int posicao                = 0;
    private int situacao               = 0;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="CONSTANTS">
    public static final int K_FORM_PESQUISA = 1;
    public static final int K_FORM_CADASTRO = 2;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Acessores">
    public Fornecedor getFornecedor(){
        return this.fornecedor;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Constructors">
    /** Creates new form FormFornecedor */
    public FormFornecedor() {
        initComponents();
        initializeMyComponents();
    }
    public FormFornecedor(Integer tipo){
        initComponents();
        initializeMyComponents();
        this.situacao = tipo;
    }
    //</editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormFornecedor().setVisible(true);
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tabGeral = new javax.swing.JTabbedPane();
        tabDescricao = new javax.swing.JPanel();
        lbDescricao = new javax.swing.JLabel();
        textDescricao = new javax.swing.JTextField();
        tabEndereco = new javax.swing.JPanel();
        lbLogradouro = new javax.swing.JLabel();
        textLogradouro = new javax.swing.JTextField();
        lbComplemento = new javax.swing.JLabel();
        textComplemento = new javax.swing.JTextField();
        lbNumero = new javax.swing.JLabel();
        textNumero = new javax.swing.JTextField();
        LbBairro = new javax.swing.JLabel();
        textBairro = new javax.swing.JTextField();
        lbCidade = new javax.swing.JLabel();
        textCidade = new javax.swing.JTextField();
        lbUF = new javax.swing.JLabel();
        cbSiglaUF = new javax.swing.JComboBox();
        LbCEP = new javax.swing.JLabel();
        textCEP = new javax.swing.JFormattedTextField();
        tabTelefone = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableTelefone = new javax.swing.JTable();
        btnNovoTel = new javax.swing.JButton();
        btnExcluirTel = new javax.swing.JButton();
        btnEditarTel = new javax.swing.JButton();
        panelBotao = new javax.swing.JPanel();
        btnBuscar = new javax.swing.JButton();
        btnNovo = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        jPanelNavegacao = new javax.swing.JPanel();
        btnFirst = new javax.swing.JButton();
        btnPrevious = new javax.swing.JButton();
        btnNext = new javax.swing.JButton();
        btnLast = new javax.swing.JButton();

        setTitle("Fornecedor");
        setName("formFornecedor"); // NOI18N
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        tabGeral.setTabPlacement(javax.swing.JTabbedPane.LEFT);
        tabGeral.setFont(new java.awt.Font("SansSerif", 0, 12));

        tabDescricao.setFont(new java.awt.Font("SansSerif", 0, 12));

        lbDescricao.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbDescricao.setText("*Descrição");

        textDescricao.setBackground(java.awt.Color.white);
        textDescricao.setEditable(false);
        textDescricao.setFont(new java.awt.Font("SansSerif", 0, 12));
        textDescricao.setMinimumSize(new java.awt.Dimension(10, 26));
        textDescricao.setPreferredSize(new java.awt.Dimension(10, 26));

        javax.swing.GroupLayout tabDescricaoLayout = new javax.swing.GroupLayout(tabDescricao);
        tabDescricao.setLayout(tabDescricaoLayout);
        tabDescricaoLayout.setHorizontalGroup(
            tabDescricaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabDescricaoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbDescricao)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 438, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        tabDescricaoLayout.setVerticalGroup(
            tabDescricaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabDescricaoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabDescricaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbDescricao)
                    .addComponent(textDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(329, Short.MAX_VALUE))
        );

        tabGeral.addTab("Informações Gerais", tabDescricao);

        tabEndereco.setFont(new java.awt.Font("SansSerif", 0, 12));

        lbLogradouro.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbLogradouro.setText("*Logradouro");

        textLogradouro.setBackground(java.awt.Color.white);
        textLogradouro.setEditable(false);
        textLogradouro.setFont(new java.awt.Font("SansSerif", 0, 12));
        textLogradouro.setMinimumSize(new java.awt.Dimension(10, 26));
        textLogradouro.setPreferredSize(new java.awt.Dimension(10, 26));

        lbComplemento.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbComplemento.setText("Complemento");

        textComplemento.setBackground(java.awt.Color.white);
        textComplemento.setEditable(false);
        textComplemento.setFont(new java.awt.Font("SansSerif", 0, 12));
        textComplemento.setMinimumSize(new java.awt.Dimension(10, 26));
        textComplemento.setPreferredSize(new java.awt.Dimension(10, 26));

        lbNumero.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbNumero.setText("Nº");

        textNumero.setBackground(java.awt.Color.white);
        textNumero.setEditable(false);
        textNumero.setFont(new java.awt.Font("SansSerif", 0, 12));
        textNumero.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textNumero.setMinimumSize(new java.awt.Dimension(10, 26));
        textNumero.setPreferredSize(new java.awt.Dimension(10, 26));

        LbBairro.setFont(new java.awt.Font("SansSerif", 0, 12));
        LbBairro.setText("*Bairro");

        textBairro.setBackground(java.awt.Color.white);
        textBairro.setEditable(false);
        textBairro.setFont(new java.awt.Font("SansSerif", 0, 12));
        textBairro.setMinimumSize(new java.awt.Dimension(10, 26));
        textBairro.setPreferredSize(new java.awt.Dimension(10, 26));

        lbCidade.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbCidade.setText("*Cidade");

        textCidade.setBackground(java.awt.Color.white);
        textCidade.setEditable(false);
        textCidade.setFont(new java.awt.Font("SansSerif", 0, 12));
        textCidade.setMinimumSize(new java.awt.Dimension(10, 26));
        textCidade.setPreferredSize(new java.awt.Dimension(10, 26));

        lbUF.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbUF.setText("*UF");

        cbSiglaUF.setBackground(java.awt.Color.white);
        cbSiglaUF.setFont(new java.awt.Font("SansSerif", 0, 12));
        cbSiglaUF.setEnabled(false);
        cbSiglaUF.setLightWeightPopupEnabled(false);
        cbSiglaUF.setMinimumSize(new java.awt.Dimension(66, 26));
        cbSiglaUF.setPreferredSize(new java.awt.Dimension(66, 26));

        LbCEP.setFont(new java.awt.Font("SansSerif", 0, 12));
        LbCEP.setText("*CEP");

        textCEP.setBackground(java.awt.Color.white);
        textCEP.setEditable(false);
        try {
            textCEP.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#####-###")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        textCEP.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        textCEP.setFont(new java.awt.Font("SansSerif", 0, 12));

        javax.swing.GroupLayout tabEnderecoLayout = new javax.swing.GroupLayout(tabEndereco);
        tabEndereco.setLayout(tabEnderecoLayout);
        tabEnderecoLayout.setHorizontalGroup(
            tabEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabEnderecoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbLogradouro)
                    .addComponent(lbComplemento)
                    .addComponent(LbBairro)
                    .addComponent(lbCidade))
                .addGap(4, 4, 4)
                .addGroup(tabEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(tabEnderecoLayout.createSequentialGroup()
                        .addGroup(tabEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(textBairro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(textCidade, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(tabEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(LbCEP)
                            .addComponent(lbUF))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(tabEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(cbSiglaUF, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(textCEP, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 79, Short.MAX_VALUE)))
                    .addGroup(tabEnderecoLayout.createSequentialGroup()
                        .addComponent(textLogradouro, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbNumero)
                        .addGap(18, 18, 18)
                        .addComponent(textNumero, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(textComplemento, javax.swing.GroupLayout.DEFAULT_SIZE, 426, Short.MAX_VALUE))
                .addGap(26, 26, 26))
        );
        tabEnderecoLayout.setVerticalGroup(
            tabEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabEnderecoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbLogradouro)
                    .addComponent(textLogradouro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbNumero)
                    .addComponent(textNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(tabEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbComplemento)
                    .addComponent(textComplemento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(tabEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(LbBairro)
                    .addGroup(tabEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(textBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(LbCEP)
                        .addComponent(textCEP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(tabEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbCidade)
                    .addGroup(tabEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(textCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(lbUF))
                    .addComponent(cbSiglaUF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(233, Short.MAX_VALUE))
        );

        tabEnderecoLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {textBairro, textCidade, textLogradouro});

        tabEnderecoLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {textCEP, textComplemento});

        tabGeral.addTab("Endereço", tabEndereco);

        tabTelefone.setFont(new java.awt.Font("SansSerif", 0, 12));

        tableTelefone.setFont(new java.awt.Font("SansSerif", 0, 12));
        tableTelefone.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Número Telefone"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableTelefone.setEnabled(false);
        jScrollPane1.setViewportView(tableTelefone);

        btnNovoTel.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnNovoTel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/new.png"))); // NOI18N
        btnNovoTel.setToolTipText("Novo");
        btnNovoTel.setEnabled(false);
        btnNovoTel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnNovoTelMouseClicked(evt);
            }
        });

        btnExcluirTel.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnExcluirTel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clear.png"))); // NOI18N
        btnExcluirTel.setToolTipText("Excluir");
        btnExcluirTel.setEnabled(false);
        btnExcluirTel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnExcluirTelMouseClicked(evt);
            }
        });

        btnEditarTel.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnEditarTel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit.png"))); // NOI18N
        btnEditarTel.setToolTipText("Editar");
        btnEditarTel.setEnabled(false);
        btnEditarTel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnEditarTelMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout tabTelefoneLayout = new javax.swing.GroupLayout(tabTelefone);
        tabTelefone.setLayout(tabTelefoneLayout);
        tabTelefoneLayout.setHorizontalGroup(
            tabTelefoneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabTelefoneLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabTelefoneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 509, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(tabTelefoneLayout.createSequentialGroup()
                        .addComponent(btnNovoTel, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(5, 5, 5)
                        .addComponent(btnEditarTel, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnExcluirTel, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        tabTelefoneLayout.setVerticalGroup(
            tabTelefoneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabTelefoneLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabTelefoneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnNovoTel)
                    .addComponent(btnEditarTel)
                    .addComponent(btnExcluirTel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 309, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tabGeral.addTab("Telefone", tabTelefone);

        panelBotao.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, java.awt.Color.gray));
        panelBotao.setFont(new java.awt.Font("DejaVu Sans", 0, 12));

        btnBuscar.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/find.png"))); // NOI18N
        btnBuscar.setText("Procurar");
        btnBuscar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnBuscarMouseClicked(evt);
            }
        });

        btnNovo.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/new.png"))); // NOI18N
        btnNovo.setText("Novo     ");
        btnNovo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnNovoMouseClicked(evt);
            }
        });

        btnCancel.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.png"))); // NOI18N
        btnCancel.setText("Cancelar");
        btnCancel.setMaximumSize(new java.awt.Dimension(92, 34));
        btnCancel.setMinimumSize(new java.awt.Dimension(92, 34));
        btnCancel.setPreferredSize(new java.awt.Dimension(92, 34));
        btnCancel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCancelMouseClicked(evt);
            }
        });

        btnExcluir.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/delete.png"))); // NOI18N
        btnExcluir.setText("Excluir   ");
        btnExcluir.setMaximumSize(new java.awt.Dimension(92, 34));
        btnExcluir.setMinimumSize(new java.awt.Dimension(92, 34));
        btnExcluir.setPreferredSize(new java.awt.Dimension(92, 34));
        btnExcluir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnExcluirMouseClicked(evt);
            }
        });

        jPanelNavegacao.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnFirst.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnFirst.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/first.png"))); // NOI18N
        btnFirst.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnFirst.setContentAreaFilled(false);
        btnFirst.setEnabled(false);
        btnFirst.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnFirstMouseClicked(evt);
            }
        });

        btnPrevious.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnPrevious.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/previous.png"))); // NOI18N
        btnPrevious.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnPrevious.setContentAreaFilled(false);
        btnPrevious.setEnabled(false);
        btnPrevious.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnPreviousMouseClicked(evt);
            }
        });

        btnNext.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnNext.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/next.png"))); // NOI18N
        btnNext.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnNext.setContentAreaFilled(false);
        btnNext.setEnabled(false);
        btnNext.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnNextMouseClicked(evt);
            }
        });

        btnLast.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnLast.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/last.png"))); // NOI18N
        btnLast.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnLast.setContentAreaFilled(false);
        btnLast.setEnabled(false);
        btnLast.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnLastMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanelNavegacaoLayout = new javax.swing.GroupLayout(jPanelNavegacao);
        jPanelNavegacao.setLayout(jPanelNavegacaoLayout);
        jPanelNavegacaoLayout.setHorizontalGroup(
            jPanelNavegacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelNavegacaoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnFirst)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnPrevious)
                .addGap(10, 10, 10)
                .addComponent(btnNext)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnLast)
                .addContainerGap())
        );
        jPanelNavegacaoLayout.setVerticalGroup(
            jPanelNavegacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelNavegacaoLayout.createSequentialGroup()
                .addGroup(jPanelNavegacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnFirst)
                    .addComponent(btnPrevious)
                    .addComponent(btnNext)
                    .addComponent(btnLast))
                .addContainerGap())
        );

        javax.swing.GroupLayout panelBotaoLayout = new javax.swing.GroupLayout(panelBotao);
        panelBotao.setLayout(panelBotaoLayout);
        panelBotaoLayout.setHorizontalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotaoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanelNavegacao, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        panelBotaoLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnBuscar, btnCancel, btnExcluir, btnNovo, jPanelNavegacao});

        panelBotaoLayout.setVerticalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelBotaoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnBuscar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnNovo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 161, Short.MAX_VALUE)
                .addComponent(jPanelNavegacao, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        panelBotaoLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnBuscar, btnCancel, btnExcluir, btnNovo});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tabGeral, javax.swing.GroupLayout.PREFERRED_SIZE, 675, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(panelBotao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(panelBotao, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(tabGeral, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE))
                .addGap(37, 37, 37))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-884)/2, (screenSize.height-430)/2, 884, 430);
    }// </editor-fold>//GEN-END:initComponents
    
    // Fecha o formulario
    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        this.setVisible(false);
        if(this.situacao == K_FORM_CADASTRO){
            this.dispose();
        }
    }//GEN-LAST:event_formWindowClosed

    //<editor-fold defaultstate="collapsed" desc="Eventos CRUD ">
    /**
     * Responsavel por persistir os objetos fornecedor, endereco e telefone.
     */
    private void btnNovoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnNovoMouseClicked
        try{
            if(btnNovo.isEnabled()){
                // Verifica o estado do botao
                if(this.btnNovo.getText().startsWith("Novo")){
                    clearFields(); // Limpa o formulario
                    StateMachineButton.changeState(getLstButton(1),
                                                       StateMachineButton.NOVO);
                    StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);

                    // Cria novas instancias de produto e endereco
                    this.fornecedor = new Fornecedor();
                    this.endereco   = new Endereco();
                    this.lstTel     = new ArrayList<Telefone>();
                    this.tabGeral.setSelectedIndex(0);
                    this.tabGeral.setVisible(true);
                    enableFields(true);
                }
                else{
                    // Verifica se todos os campos foram mapeados com sucesso
                    if(mapFields()){

                        boolean flag = false;

                        // Verifica se e um novo fornecedor ou se e para atulizar
                        if(this.fornecedor.isNew()){
                            flag =
                             this.fornecedor.insert(fornecedor, endereco, lstTel);

                            if(flag){
                                this.lstObj = null;
                                StateMachineButton.changeState(getLstButton(1),
                                                     StateMachineButton.SALVAR);
                            }
                        }
                        else{
                            flag = this.fornecedor.update(fornecedor, endereco);

                            if(flag){
                                mudarEstadoNavegacao();
                                StateMachineButton.changeState(getLstButton(1),
                                                   StateMachineButton.CANCELAR);
                            }
                        }

                        // Verifica se foi inserido com sucesso no banco de dados
                        if(flag){
                            this.fornecedor.setIsNew(false);
                            this.endereco.setIsNew(false);
                            enableFields(false);
                        }
                        else{
                            showMessageError(fornecedor.getErrorMessage());
                        }
                    }
                    else{
                        showMessageError(ErrorMessage.MSG_GERAL_OBRIG);
                    }
                }
            }
        }
        catch(IOException ex){ }
    }//GEN-LAST:event_btnNovoMouseClicked

    /**
     * Busca e recupera uma lista de fornecedores pela descricao
     */
    private void btnBuscarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnBuscarMouseClicked
        try{
            if(btnBuscar.isEnabled()){
                // Verifica o estado do botao
                if(this.btnBuscar.getText().startsWith("Procurar")){
                    clearFields(); // Limpa o formulario

                    StateMachineButton.changeState(getLstButton(1),
                                                   StateMachineButton.PROCURAR);

                    StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
                    // Seta os campos como editaveis
                    enableFields(false);
                    textDescricao.setEditable(true);
                    this.fornecedor = new Fornecedor();
                    this.tabGeral.setSelectedIndex(0);
                    this.tabGeral.setVisible(true);
                }
                else{
                    // cria uma nova lista de fornecedores
                    this.lstObj = new ArrayList();
                    mapFields();

                    lstObj =
                         this.fornecedor.recLstPessoaNome(fornecedor.getNome());

                    if(this.fornecedor.getErrorMessage().equals("")){
                        // Verifica se foi recuperado algum objeto
                        if(!lstObj.isEmpty()){
                            StateMachineNavigator.changeState(getLstButton(2),
                             lstObj.size() == 1 ?
                                 StateMachineNavigator.PADRAO :
                                 StateMachineNavigator.PRIMEIRO);

                            StateMachineButton.changeState(getLstButton(1),
                                    StateMachineButton.RECUPERAR);

                            // Apresenta o primeiro fornecedor
                            apresentaObjeto((Fornecedor)lstObj.get(0));
                        }
                        else{
                            showMessageWarning(ErrorMessage.MSG_FORNECEDOR_BUSCA);
                        }
                    }
                    else{
                        showMessageError(fornecedor.getErrorMessage());
                    }
                }
            }
        }
        catch(IOException ex){}
    }//GEN-LAST:event_btnBuscarMouseClicked

    /**
     * Cancela uma acao corrente de insercao ou edicao. Responsavel tambem por
     * abrir um registro para edicao.
     */
    private void btnCancelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelMouseClicked
        try{
            if(btnCancel.isEnabled()){
                // Verifica o estado do botao
                if(this.btnCancel.getText().startsWith("Cancelar")){

                    // Realiza a confirmacao da acao pelo usuario
                    if(JOptionPane.showConfirmDialog(this, "Confirma o cancela"
                       +"mento?", "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION){

                        enableFields(false); // Desabilita os campos

                        if(this.fornecedor.isNew()){
                            clearFields();
                            StateMachineButton.changeState(getLstButton(1),
                                                    StateMachineButton.INICIAL);
                        }
                        else{
                            StateMachineButton.changeState(getLstButton(1),
                                                   StateMachineButton.CANCELAR);
                            mudarEstadoNavegacao();
                        }
                    }
                }
                else{
                    enableFields(true);
                    this.tabGeral.setSelectedIndex(0);
                    this.tabGeral.setVisible(true);
                    this.fornecedor.setWasUpdated(true);
                    StateMachineButton.changeState(getLstButton(1),
                                                     StateMachineButton.EDITAR);
                    StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
                }
            }
        }
        catch(Exception ex){ }
    }//GEN-LAST:event_btnCancelMouseClicked

    /**
     * Exclui as informacoes de um dado fornecedor
     */
    private void btnExcluirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnExcluirMouseClicked
        try{
            if(btnExcluir.isEnabled()){
                // Realiza a confirmacao da acao pelo usuario
                if(JOptionPane.showConfirmDialog(this, "Confirma a exclusão?",
                       "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                       JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION){

                    boolean flag = this.fornecedor.
                                           delete(fornecedor, endereco, lstTel);
                    if(flag){
                        clearFields();

                        enableFields(false); // Desabilita os campos

                        // Verifica o tamanho da lista
                        if(lstObj != null){
                            // Remove o item da lista corrente
                            lstObj.remove(this.posicao);

                            // Posiciona na base de navegacao
                            mudarEstadoNavegacao();

                            if(lstObj.isEmpty()){
                                StateMachineButton.changeState(getLstButton(1),
                                                    StateMachineButton.EXCLUIR);
                            }
                            else{
                                StateMachineButton.changeState(getLstButton(1),
                                                   StateMachineButton.CANCELAR);
                            }
                        }
                        else{
                            StateMachineButton.changeState(getLstButton(1),
                                                    StateMachineButton.EXCLUIR);
                        }
                    }
                    else{
                        showMessageError(fornecedor.getErrorMessage());
                    }
                }
            }
        }
        catch(Exception ex){ }
    }//GEN-LAST:event_btnExcluirMouseClicked
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Barra Navegacao">
    /**
     * Move para a primeira posicao da lista de fornecedores
     */
    private void btnFirstMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnFirstMouseClicked
        try{
            // Verifica o tamanho da lista de fornecedores
            if(!lstObj.isEmpty() && lstObj.size() > 0 && btnFirst.isEnabled()){

                // Posiciona na posicao inicial
                StateMachineNavigator.changeState(getLstButton(2),
                                                StateMachineNavigator.PRIMEIRO);
                this.posicao = 0;
                apresentaObjeto((Fornecedor)lstObj.get(this.posicao));
            }
        }
        catch(Exception ex){ }
    }//GEN-LAST:event_btnFirstMouseClicked

    /**
     * Move para a ultima posicao da lista de fornecedores
     */
    private void btnLastMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnLastMouseClicked
        try{
            // Verifica o tamanho da lista de fornecedores
            if(!lstObj.isEmpty() && lstObj.size() > 0 && btnLast.isEnabled()){

                // Posiciona na posicao final
                StateMachineNavigator.changeState(getLstButton(2),
                                                StateMachineNavigator.ULTIMO);
                this.posicao = lstObj.size() - 1;
                apresentaObjeto((Fornecedor)lstObj.get(this.posicao));
            }
        }
        catch(Exception ex){ }
    }//GEN-LAST:event_btnLastMouseClicked

    /**
     * Posiciona na posicao anterior da lista
     */
    private void btnPreviousMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnPreviousMouseClicked
        try{
            // Verifica o tamanho da lista de fornecedores
            if(!lstObj.isEmpty() && lstObj.size() > 0 && btnPrevious.isEnabled()){

                this.posicao--; // Recebe a proxima posicao

                if(this.posicao >= 1){
                    StateMachineNavigator.changeState(getLstButton(2),
                                          StateMachineNavigator.ANTERIOR_MAIOR);
                }
                else{
                    StateMachineNavigator.changeState(getLstButton(2),
                                          StateMachineNavigator.ANTERIOR_MENOR);
                }

                apresentaObjeto((Fornecedor)lstObj.get(this.posicao));
            }
        }
        catch(Exception ex){ }
    }//GEN-LAST:event_btnPreviousMouseClicked

    /**
     * Move para a proxima unidade da lista de fornecedores
     */
    private void btnNextMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnNextMouseClicked
        // TODO add your handling code here:
        try{
            // Verifica o tamanho da lista de fornecedores
            if(!lstObj.isEmpty() && lstObj.size() > 0 && btnNext.isEnabled()){

                this.posicao++; // Recebe a proxima posicao

                if(this.posicao >= (lstObj.size() - 1)){
                    StateMachineNavigator.changeState(getLstButton(2),
                                          StateMachineNavigator.PROXIMO_MENOR);
                }
                else{
                    StateMachineNavigator.changeState(getLstButton(2),
                                          StateMachineNavigator.PROXIMO_MAIOR);
                }

                apresentaObjeto((Fornecedor)lstObj.get(this.posicao));
            }
        }
        catch(Exception ex){ }
    }//GEN-LAST:event_btnNextMouseClicked
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="Controle de Telefones">
    // Responsavel pela insercao de um novo telefone
    private void btnNovoTelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnNovoTelMouseClicked
        try{
            if(btnNovoTel.isEnabled()){
                FormIncludeTel form = new FormIncludeTel();
                form.setModal(true);
                form.setNumTelefone(null);
                form.setVisible(true);
                String numTel = form.getNumTelefone();
                form.dispose();

                if(numTel != null) insereTelefone(numTel);
            }
        }
        catch(IOException ex){}
    }//GEN-LAST:event_btnNovoTelMouseClicked

    // Realiza a exclusao de um telefone
    private void btnExcluirTelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnExcluirTelMouseClicked
        try{
            if(btnExcluirTel.isEnabled()) removeTelefone();
        }
        catch(Exception ex){}
    }//GEN-LAST:event_btnExcluirTelMouseClicked

    // Realiza a edicao de um telefone
    private void btnEditarTelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEditarTelMouseClicked
        try{
            if(btnEditarTel.isEnabled()){
                // Recebe o registro corrente da tabela
                int selected = tableTelefone.getSelectedRow();

                if(selected > -1){
                    Telefone tel = lstTel.get(selected);

                    FormIncludeTel form = new FormIncludeTel(tel.getNumero());
                    form.setModal(true);
                    form.setVisible(true);

                    String newNumber = form.getNumTelefone();
                    form.dispose();

                    // Verifica se o telefone foi alterado
                    if(!tel.getNumero().equals(newNumber))
                        alterTelefone(selected, newNumber);
                }
                else{
                   showMessageWarning(ErrorMessage.MSG_GERAL_SELECAO);
                }
            }
        }
        catch(Exception ex){}
    }//GEN-LAST:event_btnEditarTelMouseClicked
    //</editor-fold>

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel LbBairro;
    private javax.swing.JLabel LbCEP;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnEditarTel;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnExcluirTel;
    private javax.swing.JButton btnFirst;
    private javax.swing.JButton btnLast;
    private javax.swing.JButton btnNext;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnNovoTel;
    private javax.swing.JButton btnPrevious;
    private javax.swing.JComboBox cbSiglaUF;
    private javax.swing.JPanel jPanelNavegacao;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbCidade;
    private javax.swing.JLabel lbComplemento;
    private javax.swing.JLabel lbDescricao;
    private javax.swing.JLabel lbLogradouro;
    private javax.swing.JLabel lbNumero;
    private javax.swing.JLabel lbUF;
    private javax.swing.JPanel panelBotao;
    private javax.swing.JPanel tabDescricao;
    private javax.swing.JPanel tabEndereco;
    private javax.swing.JTabbedPane tabGeral;
    private javax.swing.JPanel tabTelefone;
    private javax.swing.JTable tableTelefone;
    private javax.swing.JTextField textBairro;
    private javax.swing.JFormattedTextField textCEP;
    private javax.swing.JTextField textCidade;
    private javax.swing.JTextField textComplemento;
    private javax.swing.JTextField textDescricao;
    private javax.swing.JTextField textLogradouro;
    private javax.swing.JTextField textNumero;
    // End of variables declaration//GEN-END:variables

    //<editor-fold defaultstate="collapsed" desc="Methods">
    // Messagem de erro
    private void showMessageError(String msg){
        JOptionPane.showMessageDialog(this, msg, "Fornecedor",
                                                    JOptionPane.ERROR_MESSAGE);
    }

    // Messagem de alerta
    private void showMessageWarning(String msg){
        JOptionPane.showMessageDialog(this, msg, "Fornecedor",
                                                   JOptionPane.WARNING_MESSAGE);
    }

    // Recupera a lista de botoes do formulario
    private ArrayList<JButton> getLstButton(Integer situacao){
        ArrayList<JButton> lstButton = new ArrayList<JButton>();

        if(situacao == 1){
            lstButton.add(this.btnBuscar);
            lstButton.add(this.btnNovo);
            lstButton.add(this.btnCancel);
            lstButton.add(this.btnExcluir);
        }
        else{
            lstButton.add(this.btnFirst);
            lstButton.add(this.btnPrevious);
            lstButton.add(this.btnNext);
            lstButton.add(this.btnLast);
        }

        return lstButton;
    }

    // Insere os estados no combobox
    private void populateCombo(){
        // Cria uma nova instancia e recupera todos os estados pertencentes
        ArrayList<String> lstEstados = new ArrayList<String>();
        lstEstados = Estado.getLstValues(Estado.class);

        for(String uf : lstEstados){
            this.cbSiglaUF.addItem(uf);
        }
    }

    // Limpa os campos do formulario
    private void clearFields(){
        textDescricao.setText("");
        textLogradouro.setText("");
        textNumero.setText("");
        textComplemento.setText("");
        textBairro.setText("");
        textCEP.setText(null);
        textCidade.setText("");
        cbSiglaUF.setSelectedIndex(0);

        DefaultTableModel def = (DefaultTableModel)tableTelefone.getModel();
        def.getDataVector().clear();
        tableTelefone.updateUI();
    }

    // Configura a tabela para apresentacao
    private void configureTable(){
        tableTelefone.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    // Controle dos campos para edicao
    private void enableFields(Boolean flag){
        textDescricao.setEditable(flag);
        textLogradouro.setEditable(flag);
        textNumero.setEditable(flag);
        textComplemento.setEditable(flag);
        textBairro.setEditable(flag);
        textCEP.setEditable(flag);
        textCidade.setEditable(flag);
        cbSiglaUF.setEnabled(flag);
        btnNovoTel.setEnabled(flag);
        btnExcluirTel.setEnabled(flag);
        btnEditarTel.setEnabled(flag);
        tableTelefone.setEnabled(flag);
    }

    // Transfere os campos para o objeto para persistencia
    private Boolean mapFields(){
        boolean map = true;

        try{
            // Uppercase nos campos
            textDescricao.setText(textDescricao.getText().toUpperCase());
            textLogradouro.setText(textLogradouro.getText().toUpperCase());
            textComplemento.setText(textComplemento.getText().toUpperCase());
            textBairro.setText(textBairro.getText().toUpperCase());
            textCidade.setText(textCidade.getText().toUpperCase());

            // Mapeia o campo do fornecedor
            this.fornecedor.setNome(textDescricao.getText());

            if(this.endereco != null){
            // Mapeia os campos de endereco
                this.endereco.setLogradouro(textLogradouro.getText());
                this.endereco.setComplemento(textComplemento.getText());
                this.endereco.setCidade(textCidade.getText());
                this.endereco.setBairro(textBairro.getText());
                this.endereco.setNumero(textNumero.getText().isEmpty() ?
                         0 : Integer.parseInt(textNumero.getText()));
                this.endereco.setCep(textCEP.getText());
                this.endereco.setEstado(cbSiglaUF.getSelectedIndex() + 1);
            }
        }
        catch(ArithmeticException ex){
            ex.printStackTrace();
            map = false;
        }
        return map;
    }

    // Realiza a apresentacao do fornecedor juntamente com seus dados
    private void apresentaObjeto(Fornecedor obj){

        enableFields(false);
        // Apresenta o fornecedor em questao
        this.fornecedor = obj;
        this.textDescricao.setText(obj.getNome());

        // Recupera e apresenta o endereco do fornecedor selecionado
        if(this.endereco == null) this.endereco = new Endereco();

        this.endereco = this.endereco.recEnderecoPessoa(obj.getCod_objeto());

        textLogradouro.setText(this.endereco.getLogradouro());
        textComplemento.setText(this.endereco.getComplemento());
        textCidade.setText(this.endereco.getCidade());
        textBairro.setText(this.endereco.getBairro());
        textNumero.setText(this.endereco.getNumero() == 0 ? "" :
                                 String.valueOf(this.endereco.getNumero()));
        textCEP.setText(this.endereco.getCep());
        cbSiglaUF.setSelectedIndex(this.endereco.getEstado() - 1);

        // Recupera a lista de telefones para o fornecedor
        if(this.lstTel == null) this.lstTel = new ArrayList<Telefone>();

        Telefone tel = new Telefone();
        this.lstTel = tel.recLstTelefonesPessoa(obj.getCod_objeto());

        // Verifica se foi encontrado algum telefone para apresentacao
        DefaultTableModel def = (DefaultTableModel)tableTelefone.getModel();
        def.getDataVector().clear();
        tableTelefone.updateUI();

        for(Telefone t : lstTel){
            Object[] row = new Object[]{t.getNumero()};
            def.addRow(row);
        }
    }

    // Inicializa o estados de todos os botoes
    private void initializeMyComponents(){
        try{
            StateMachineButton.changeState(getLstButton(1),
                                                  StateMachineButton.INICIAL);
            StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
            populateCombo();
            clearFields();
            configureTable();
        }
        catch(IOException ex){}
    }

    // Volta ao estado da navegacao
    private void mudarEstadoNavegacao() throws IOException{

        if(lstObj != null){
            // Verifica se existe a posicao na lista
            boolean exists = this.posicao < this.lstObj.size() ? true : false;

            // Decrementa uma posicao caso a ultima tenha sido removida
            if(!exists) this.posicao--;

            // Verifica se a lista esta vazia
            if(lstObj.isEmpty()){
                clearFields();
                StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
            }
            // Verifica se o tamanho da lista e 1
            else{
                apresentaObjeto((Fornecedor)lstObj.get(this.posicao));

                if(lstObj.size() <= 1){
                    StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
                }
                else{
                    // Verifica qual a posicao que se encontra
                    if(this.posicao == 0){
                        StateMachineNavigator.changeState(getLstButton(2),
                                                StateMachineNavigator.PRIMEIRO);
                    }
                    else if(this.posicao == (lstObj.size() - 1)){
                        StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.ULTIMO);
                    }
                    else{
                        StateMachineNavigator.changeState(getLstButton(2),
                                          StateMachineNavigator.ANTERIOR_MAIOR);
                    }
                }
            }
        }
    }

    // Insere os telefones na lista de telefones
    private void insereTelefone(String numTel) throws IOException{

        // Verifica se a lista de telefones e nula para realizar a criacao
        if(lstTel == null) lstTel = new ArrayList<Telefone>();

        DefaultTableModel def = (DefaultTableModel)tableTelefone.getModel();
        tableTelefone.updateUI();

        /**
         * Caso o fornecedor for novo o mesmo e apenas acrescido na lista para
         * insercao posterior. Caso contrario, o mesmo e inserido
         * instantaneamente.
         */
        Telefone t = new Telefone();
        t.setNumero(numTel);

        if(this.fornecedor.isNew()){
            lstTel.add(t);
            Object[] row = new Object[]{t.getNumero()};
            def.addRow(row);
        }
        else{
            t.setPessoa(this.fornecedor.getCod_objeto());
            if(t.insert()){
                Object[] row = new Object[]{t.getNumero()};
                def.addRow(row);
            }
            else{
                showMessageError(t.getErrorMessage());
            }
        }
    }

    // Remove um telefone da lista de telefones do usuario
    private void removeTelefone() throws IOException{
        // Pega o registro corrente do grid
        int selected = tableTelefone.getSelectedRow();

        // Verifica se foi selecionado algum registro
        if(selected > -1){
            DefaultTableModel def = (DefaultTableModel)tableTelefone.getModel();
            tableTelefone.updateUI();

            /**
             * Deve-se primeiramente verificar se a fornecedor esta sendo
             * cadastrado. Se sim, basta remover da lista. Caso contrario,
             * deve ser feita a remocao da base de dados e da lista.
             */
            if(this.fornecedor.isNew()){
                this.lstTel.remove(selected);
                def.removeRow(selected);
            }
            else{
                Telefone t = (Telefone)this.lstTel.get(selected);
                
                if(t.delete()){
                    this.lstTel.remove(selected);
                    def.removeRow(selected);
                }
                else{
                    showMessageError(t.getErrorMessage());
                }
            }
        }
        else{
           showMessageWarning(ErrorMessage.MSG_GERAL_SELECAO);
        }
    }

    // Altera o telefone para um dado fornecedor
    private void alterTelefone(int index, String numTelefone) throws IOException{

        Telefone tel = lstTel.get(index);
        DefaultTableModel def = (DefaultTableModel)tableTelefone.getModel();
            tel.setNumero(numTelefone);
        boolean alter = true;

        /**
         * Caso o fornecedor ainda nao tenha sido cadastrado o mesmo e apenas
         * alterado na lista, caso contrario, o mesmo e alterado na base de
         * dados.
         */
        if(!this.fornecedor.isNew()){
            alter = tel.update();
        }

        if(alter){
            def.setValueAt(numTelefone, index, 0);
        }
        else{
            showMessageError(tel.getErrorMessage());
        }
    }
    //</editor-fold>
}